﻿using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace SBarth.TheLionsShare
{
    public partial class ContactUs : System.Web.UI.Page
    {
        protected static readonly ILog log = LogManager.GetLogger(typeof(ContactUs));

        protected void Page_Load(object sender, EventArgs e)
        {
            log.Debug("Initialising ....");

            // Show this page as active in navigation bar
            Site sm = (Site)Page.Master;
            sm.ShowActivePage(SBarth.TheLionsShare.Site.WebPage.ContactUs);
        }
        

        protected void Send_Email(object sender, EventArgs e)
        {
            log.Debug("Do send email");
            log.Debug("Validating email form");

            // TODO: Check if we need this
            //Page.Validate();

            ErrorObj err = isValidForm();

            if (err.IsValidForm && Page.IsValid)
            {
                try
                {
                    log.Debug("Email form valid, attempting to send email...");

                    string emailBody = "Name: " + txtName.Text + "\n" +
                                       "Email Address: " + txtEmailAddress.Text + "\n" +
                                       "Phone Number: " + txtPhone.Text + "\n" +
                                       "Message: " + txtEmailBody.Text;
                    CommonUtils.SendMail(txtEmailAddress.Text, emailBody);

                    doClearForm();
                    displayMessage("Message successfully sent, we'll get back to your shortly!");
                }

                catch (SmtpFailedRecipientException ex)
                {
                    // Failure when sending to one of the recipients
                    log.Fatal(ex.GetBaseException().Message.ToString() + "\n" + ex.GetBaseException().StackTrace.ToString());
                    displayMessage("An error occurred while sending the email, please contact the System Administrator for assistance");
                }

                catch (SmtpException ex)
                {
                    // Catch all - most likely connection error

                    // As per http://msdn.microsoft.com/en-us/library/swas0fwc.aspx
                    // If you receive an SmtpException exception, check the StatusCode property to find 
                    // the reason the operation failed. The SmtpException can also contain an inner exception 
                    // that indicates the reason the operation failed.

                    log.Fatal(ex.GetBaseException().ToString() + "\n" + ex.GetBaseException().StackTrace.ToString());
                    displayMessage("An error occurred while sending the email, please contact the System Administrator for assistance");
                }
            }
            else
            {
                // Form is invalid
                log.Debug(err.ErrorMessages);

                String ErrorMessage = "Error(s): " + Environment.NewLine +
                                      "<ul id='lstErrors'>";
                foreach (string m in err.ErrorMessages) 
                {
                    ErrorMessage += "<li>" + m + "</li>";
                }
                ErrorMessage += Environment.NewLine + "</ul>";

                displayMessage(ErrorMessage);
            }
        }


        protected void doClearForm()
        {
            txtName.Text = "";
            txtEmailAddress.Text = "";
            txtPhone.Text = "";
            txtEmailBody.Text = "";
            txtChallenge.Value = "";
        }


        ErrorObj isValidForm ()
        {
            ErrorObj e = new ErrorObj();
            e.IsValidForm = true;

            if (CommonUtils.IsEmptyOrNull(txtName.Text))
            {
                e.ErrorMessages.Add("Invalid Name, a Name must be entered");
                e.IsValidForm = false;
            }

            if (CommonUtils.IsEmptyOrNull(txtEmailAddress.Text))
            {
                e.ErrorMessages.Add("Invalid Email Address, an Email Address must be entered");
                e.IsValidForm = false;
            }

            if (!CommonUtils.IsEmptyOrNull(txtEmailAddress.Text) && !CommonUtils.IsValidEmail(txtEmailAddress.Text))
            {
                e.ErrorMessages.Add("Invalid Email Address format");
                e.IsValidForm = false;
            }

            if (CommonUtils.IsEmptyOrNull(txtEmailBody.Text))
            {
                e.ErrorMessages.Add("Invalid Message, an Email Message must be entered");
                e.IsValidForm = false;
            }

            if (txtName.Text.Length > 100 || txtEmailAddress.Text.Length > 100 || txtPhone.Text.Length > 30 || txtEmailBody.Text.Length > 2000)
            {
                e.ErrorMessages.Add("Invalid field lengths(s)");
                e.IsValidForm = false;
            }

            if (!CommonUtils.IsEmptyOrNull(txtPhone.Text) && !CommonUtils.IsValidPhoneNumber(txtPhone.Text))
            {
                e.ErrorMessages.Add("Invalid Phone Number format");
                e.IsValidForm = false;
            }

            if (CommonUtils.IsEmptyOrNull(txtChallenge.Value) || txtChallenge.Value != Server.HtmlEncode(Session.SessionID.Substring(3, 5) + Session.SessionID.Substring(0, 2)))
            {
                e.ErrorMessages.Add("Sorry no can do because you're an evil spam bot :)");
                e.IsValidForm = false;
            }

            return e;
        }


        void displayMessage(string msg)
        {
            contactus_form_container6.Attributes.Remove("class");  // Display the control
            contactus_form_container6.InnerHtml = msg;
        }

    }


    public class ErrorObj
    {
        public bool IsValidForm { get; set; }
        public List<string> ErrorMessages { get; set; }

        public ErrorObj()
        {
            IsValidForm = true;
            ErrorMessages = new List<string>();
        }
    }
}


